﻿using System;
using System.Text.RegularExpressions;

namespace SlamDunk.MES.DataDrive.Common
{
    /// <summary>
    /// 字符串扩展类
    /// </summary>
    public static class StringExtension
    {
        /// <summary>
        /// 获取字符串中所包含的小括号内的值
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="resultIndex">内索引，例如：$1</param>
        /// <returns>如果无法匹配返回源字符内容</returns>
        public static string GetPrecedenceValue(this string str, string resultIndex = "$1")
        {
            str = str.Replace("（", ")");
            str = str.Replace("）", ")");
            Regex reg = new Regex(@"\(([^)]*)\)");
            try
            {
                return reg.Match(str).Result(resultIndex);
            }
            catch (Exception e)
            {
                return str;
            }
        }
        /// <summary>
        /// 根据字符串返回对应枚举类型
        /// </summary>
        /// <typeparam name="T">对应枚举类型</typeparam>
        /// <param name="source">字符串</param>
        /// <returns></returns>
        public static T ToEnum<T>(this string source)
        {
            if (typeof(T).BaseType == typeof(Enum))
            {
                foreach (T value in Enum.GetValues(typeof(T)))
                {
                    if (source == value.ToString())
                    {
                        return value;
                    }
                }
            }
            else
            {
                throw new ArgumentException("T必须为枚举类型");
            }

            return default(T);
        }
    }
}